package com.dhj.yygh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dhj.yygh.client.DictFeignClient;
import com.dhj.yygh.mapper.PatientMapper;
import com.dhj.yygh.model.user.Patient;
import com.dhj.yygh.service.PatientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PatientServiceImpl extends ServiceImpl<PatientMapper, Patient> implements PatientService {

    // dict 远程调用
    @Autowired
    DictFeignClient dictFeignClient;

    /**
     * 根据用户 id 获取就诊人信息
     *
     * @param userId 用户 id
     * @return 返回就诊人集合
     */
    @Override
    public List<Patient> findAllByUserId(Long userId) {
        QueryWrapper<Patient> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        List<Patient> patients = baseMapper.selectList(wrapper);

        // 遍历设置额外信息: 省份 | 城市
        for (Patient patient : patients) {
            setPatientParam(patient);
        }

        return patients;
    }


    /**
     * 根据就诊人 id 获取就诊人信息
     *
     * @param id 就诊人 id
     * @return 返回就诊人 id
     */
    @Override
    public Patient getPatientById(Long id) {

        Patient patient = baseMapper.selectById(id);

        setPatientParam(patient);

        return patient;
    }


    /**
     * 设置就诊人相关参数
     *
     * @param patient 就诊人对象
     */
    private void setPatientParam(Patient patient) {
        // 省 | 市 | 地区
        String provinceName = dictFeignClient.getDictByValue(patient.getProvinceCode());
        String cityName = dictFeignClient.getDictByValue(patient.getCityCode());
        String districtName = dictFeignClient.getDictByValue(patient.getDistrictCode());

        // 根据 dictcode 和 证件类型编号 查询 就诊人 和 就诊人联系人 的证件类型名称
        String certificatesName =
                dictFeignClient.getDictByDictcodeAndValue("CertificatesType", patient.getCertificatesType());
        String contactsCertificatesName =
                dictFeignClient.getDictByDictcodeAndValue("CertificatesType", patient.getContactsCertificatesType());

        // 封装参数
        patient.getParam().put("provinceName", provinceName);
        patient.getParam().put("cityName", cityName);
        patient.getParam().put("districtName", districtName);
        patient.getParam().put("certificatesName", certificatesName);// 就诊人证件类型
        patient.getParam().put("contactsCertificatesName", contactsCertificatesName);// 就诊人联系人证件类型
        patient.getParam().put("fullAddress",
                provinceName + " | "
                        + cityName + " | "
                        + districtName + "|"
                        + patient.getAddress());// 详细地址
    }
}
